﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Data;
using GalaSoft.MvvmLight.Command;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.AppCode.Helpers;
using Rio.Framework.Pages.ChildWindows;
using Rio.Framework.Pages.Context;
using NetBay.Core.Silverlight.Extensions;
using Rio.Framework.Pages.Helpers.Converter;
using Rio.Framework.Pages.Manager;
using Rio.Framework.Pages.ModalControls;
using Rio.Framework.WCFService;
using Rio.Framework.WCFService.RioWcfServices;
using Telerik.Windows;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Data;
using Folder = NetBay.Core.BusinessEntities.Folder;
using Index = NetBay.Core.BusinessEntities.Index;
using System.Text;

namespace Rio.Framework.Pages.Controls
{
    public delegate void LoadModificationSelectedFolderhHandler(Folder folder);
    public delegate void DocumentPastedHandler(object sender, Folder folder);

    public sealed partial class ListFolderControl
    {
        #region Attributs

        public event EventHandler CreateAlertEventHandler;
        private List<Folder> _listFolders;
        private ListDocumentControl _rowDetailControl;

        #endregion

        #region Properties

        public RadMenuItem ButtonAlert
        {
            get { return this.buttonAlert; }
        }

        public QueryableCollectionView Folders
        {
            get { return m_oSource; }
            set
            {
                m_oSource = value;
                OnPropertyChanged("Folders");
            }
        }

        /// <summary>
        ///  List of Folders in the gridview
        /// </summary>
        public List<Folder> ListFolders
        {
            get { return _listFolders; }
            set
            {
                _listFolders = value;

                LoadListFolders();
                if (value.Count == 1 && HtmlPage.Document.DocumentUri.OriginalString.Contains("?"))
                {
                    GridViewDoc.SelectedItems.Clear();
                    GridViewDoc.SelectedItems.Add(m_oSource.GetItemAt(0));
                    OpenFolderClick();
                }

                // Disable delete button if user can't modify folder
                buttonDelete.Visibility = (GlobalWebContext.GetUserCanDelete(FolderTypeSelected)) ? Visibility.Visible : Visibility.Collapsed;

            }
        }

        /// <summary>
        /// 
        /// </summary>
        public double ActualSearchPanelWidth { get; set; }

        #endregion

        #region Events

        public event LoadModificationSelectedDocumenthHandler LoadModificationSelectedDocument;
        public event LoadModificationSelectedFolderhHandler LoadModificationSelectedFolder;

        #endregion

        #region Constructors

        public ListFolderControl()
        {
            InitializeComponent();

            m_ssSplashScreen = new SplashScreen();

            InitLabel();

            //Add double click event at the gridview
            GridViewDoc.AddHandler(GridViewCellBase.CellDoubleClickEvent,
                                   new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick),
                                   true);
        }

        public ListFolderControl(List<Index> listIndex)
            : this()
        {
            ListIndex = listIndex;
        }

        #endregion

        #region Row detail for folder
        /// <summary>
        /// Expand row details
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridViewDocRowDetailsVisibilityChanged(object sender, GridViewRowDetailsEventArgs e)
        {
            if (e.Visibility == Visibility.Visible)
            {
                if ((m_gvrLastExpandedRow != null) && (m_gvrLastExpandedRow.DetailsVisibility == Visibility.Visible))
                {
                    m_gvrLastExpandedRow.DetailsVisibility = Visibility.Collapsed;
                }

                m_gvrLastExpandedRow = e.Row;

                //Row detail control selected
                _rowDetailControl = (ListDocumentControl)e.DetailsElement;
                _rowDetailControl.UpdatePageSize(15);

                if ((e.Row != null) && (e.Row.Item != null))
                {
                    //Launch Splash screen
                    m_ssSplashScreen.Show();
                    ModalDialogController.Launch(m_ssSplashScreen);

                    Dictionary<string, Object> dict = e.Row.Item as Dictionary<string, Object>;
                    if (dict != null)
                    {
                        long folderIdentifier = (long)dict["Identifier"];
                        long folderTypeIdentifier = _listFolders.First().FolderTypeIdentifier;

                        LoadDocumentOnFolder(folderTypeIdentifier, folderIdentifier);
                    }
                }
            }
            else
            {
                m_gvrLastExpandedRow = null;
            }
        }

        /// <summary>
        /// Load a folder's documents in selected row gridview's detail row
        /// </summary>
        /// <param name="folderTypeIdentifier"></param>
        /// <param name="folderIdentifier"></param>
        private void LoadDocumentOnFolder(long folderTypeIdentifier, long folderIdentifier)
        {
            var query = GlobalWebContext.BusinessEntitiesDomainContext.GetDocumentsQuery(folderTypeIdentifier, folderIdentifier);
            GlobalWebContext.BusinessEntitiesDomainContext.Load(query, OnGetDocumentByFolderQueryCallback, null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="result"></param>
        public void OnGetDocumentByFolderQueryCallback(LoadOperation<NetBay.Core.BusinessEntities.Document> result)
        {
            if (_rowDetailControl != null)
            {
                //load folder's documents in row detail
                _rowDetailControl.ListDocuments = new List<NetBay.Core.BusinessEntities.Document>(result.Entities);
            }

            ModalDialogController.Close();
            m_ssSplashScreen.Close();
        }

        private void ListDocumentControlLoaded(object sender, RoutedEventArgs e)
        {
            ListDocumentControl listDocumentControl = (ListDocumentControl)sender;
            listDocumentControl.LoadModificationSelectedDocument += ListDocumentControlLoadModificationSelectedDocument;
        }

        private void ListDocumentControlLoadModificationSelectedDocument(NetBay.Core.BusinessEntities.Document document)
        {
            LoadModificationSelectedDocument(document);
        }

        #endregion

        #region Context Menu
        private void RadContextMenuItemClick(object sender, RadRoutedEventArgs e)
        {
            string contextMenuName = ((RadMenuItem)e.OriginalSource).Name;

            switch (contextMenuName)
            {
                case "DeleteItemContextMenu":
                    OnFolderDeleteClick();
                    break;
                case "ExportExcelContextMenu":
                    OnExportClick();
                    break;
                case "OpenFolderContextMenu":
                    OpenFolderClick();
                    break;
                case "AddDocumentContextMenu":
                    OnAddDocumentClick();
                    break;
                case "DisplayFolderNoteContextMenu":
                    OnOpenFolderNoteClick();
                    break;
                case "PrintMenuContextMenu":
                    OnPrintMenuClick();
                    break;
                case "CreateReportContextMenu":
                    OnCreateReportClick();
                    break;
                case "PasteMenuContextMenu":
                    OnPastClick();
                    break;
                case "DownloadFolderContextMenu":
                    OnDownloadFolderClick();
                    break;
            }
        }

        private void RadContextMenuOpened(object sender, RoutedEventArgs e)
        {

            switch (GridViewDoc.SelectedItems.Count)
            {
                case 0:
                    {
                        ((RadContextMenu)sender).IsOpen = false;
                        break;
                    }
                case 1:
                    {
                        OpenFolderContextMenu.IsEnabled = true;
                        AddDocumentContextMenu.IsEnabled = (GlobalWebContext.GetUserCanScann(FolderTypeSelected));
                        DisplayFolderNoteContextMenu.IsEnabled = true;
                        DeleteItemContextMenu.IsEnabled = (GlobalWebContext.GetUserCanDelete(FolderTypeSelected));
                        PrintMenuContextMenu.IsEnabled = (GlobalWebContext.GetUserCanPrint(FolderTypeSelected));
                        PasteMenuContextMenu.IsEnabled = isPastEnabled;
                        ExportExcelContextMenu.IsEnabled = (GlobalWebContext.GetUserCanDownload(FolderTypeSelected));
                        DownloadFolderContextMenu.IsEnabled = (GlobalWebContext.GetUserCanDownload(FolderTypeSelected));
                        break;
                    }
                default:
                    {
                        OpenFolderContextMenu.IsEnabled = false;
                        AddDocumentContextMenu.IsEnabled = false;
                        DisplayFolderNoteContextMenu.IsEnabled = false;
                        DeleteItemContextMenu.IsEnabled = (GlobalWebContext.GetUserCanDelete(FolderTypeSelected));
                        PrintMenuContextMenu.IsEnabled = false;
                        PasteMenuContextMenu.IsEnabled = false;
                        ExportExcelContextMenu.IsEnabled = (GlobalWebContext.GetUserCanDownload(FolderTypeSelected));
                        DownloadFolderContextMenu.IsEnabled = (GlobalWebContext.GetUserCanDownload(FolderTypeSelected));
                        break;
                    }
            }
        }
        #endregion

        #region AddDocument

        private void OnAddDocumentClick()
        {
            Dictionary<string, Object> dict = GridViewDoc.SelectedItem as Dictionary<string, Object>;
            if (dict != null)
            {
                Folder selectedFolder = _listFolders.Where(f => f.Identifier == (long)dict["Identifier"]).FirstOrDefault();


                AddDocumentChildWindow addDocumentChildWindow = new AddDocumentChildWindow(
                    FolderTypeSelected,
                    OrganizationSelected,
                    selectedFolder,
                    Int32.Parse(GlobalWebContext.RioAppSettings["MaxNumberOfFilesImported"]))
                {
                    Width = ActualWidth + ActualSearchPanelWidth,
                    Height = ActualHeight
                };

                addDocumentChildWindow.Closed += AddDocumentChildWindowClosed;
                addDocumentChildWindow.ShowDialog();
            }
        }

        private void AddDocumentChildWindowClosed(object sender, WindowClosedEventArgs e)
        {
            OnRefreshSearchResult();
        }

        #endregion

        #region Open Folder Note

        private void OnOpenFolderNoteClick()
        {
            Dictionary<string, Object> dict = GridViewDoc.SelectedItem as Dictionary<string, Object>;
            if (dict != null)
            {
                Folder selectedFolder = _listFolders.Where(f => f.Identifier == (long)dict["Identifier"]).FirstOrDefault();

                if (selectedFolder != null)
                {
                    CommentChildWindow folderComment = new CommentChildWindow { Header = "Commentaire dossier", Comment = selectedFolder.Note };
                    folderComment.Closed += FolderCommentClosed;
                    folderComment.ShowDialog();
                }
            }
        }

        private void FolderCommentClosed(object sender, EventArgs e)
        {
            Dictionary<string, Object> dict = GridViewDoc.SelectedItem as Dictionary<string, Object>;
            if (dict != null)
            {
                Folder selectedFolder =
                                _listFolders.Where(f => f.Identifier == (long)dict["Identifier"]).FirstOrDefault();


                CommentChildWindow folderComment = (CommentChildWindow)sender;
                if (folderComment.DialogResult == true)
                {
                    if (selectedFolder != null)
                    {
                        var query = GlobalWebContext.BusinessEntitiesDomainContext.UpdateFolderCommentQuery(selectedFolder.FolderTypeIdentifier,
                                                                                    selectedFolder.Identifier,
                                                                                    selectedFolder.Iddoc,
                                                                                    folderComment.Comment);
                        GlobalWebContext.BusinessEntitiesDomainContext.Load(query, UpdateFolderCommentQueryCallback, null);
                    }
                }
            }
        }

        /// <summary>
        /// Call back of the UpdateFolderCommentQuery action
        /// </summary>
        /// <param name="result"></param>
        public void UpdateFolderCommentQueryCallback(LoadOperation result)
        {
            if (result.HasError)
            {
                MessageBoxChildWindow message = new MessageBoxChildWindow(String.Empty, "Une erreur s'est produite lors de la mise à jour du commentaire", MessageBoxButtons.Ok, MessageBoxIcon.Information);
                message.ShowDialog();
            }
            else
            {
                OnRefreshSearchResult();
            }
        }
        #endregion

        #region Open Folder

        private void ButtonDisplayClick(object sender, RoutedEventArgs e)
        {
            OpenFolderClick();
        }

        /// <summary>
        /// Open the folder according to the selected cell
        /// </summary>
        /// <param name="sender"></param>
        private void OpenFolderClick()
        {
            Dictionary<string, Object> dict = null;
            if (GridViewDoc.SelectedItem != null)
            {

                dict = GridViewDoc.SelectedItem as Dictionary<string, Object>;
            }
            else
            {
                if (GridViewDoc.SelectedItems.Count > 0)
                    dict = GridViewDoc.SelectedItems[0] as Dictionary<string, Object>;
            }

            if (dict != null)
            {
                Folder selectedFolder = _listFolders.Where(f => f.Identifier == (long)dict["Identifier"]).FirstOrDefault();
                if (selectedFolder != null)
                {
                    LoadModificationSelectedFolder(selectedFolder);
                }
            }
        }

        #endregion

        #region Folder Delete
        /// <summary>
        /// Event called by the delet button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonDeleteClick(object sender, RoutedEventArgs e)
        {
            OnFolderDeleteClick();
        }

        private void OnFolderDeleteClick()
        {

            List<Folder> selectedFolders = new List<Folder>();
            if (GridViewDoc.SelectedItems != null && GridViewDoc.SelectedItems.Count > 0)
            {
                selectedFolders.AddRange(GridViewDoc.SelectedItems.Cast<Dictionary<string, Object>>().Select(item => _listFolders.Where(f => f.Identifier == (long)item["Identifier"]).FirstOrDefault()).Where(f => f != null));

                MessageBoxChildWindow message = new MessageBoxChildWindow("", labelMessageDeleteConfirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                message.ShowDialog();

                message.Closed += (s, ev) =>
                {
                    if (message.Result == MessageBoxResult.Yes)
                    {
                        DeleteFolders(selectedFolders);
                    }
                };
            }

        }

        private void DeleteFolders(List<Folder> listFolder)
        {
            try
            {
                if (m_oFolderTypeFlow != FlowEnums.ChronoTypeEnum.None)
                {
                    Folder folder = listFolder[0];

                    List<Index> indexList = folder.ListIndex.ToList();
                    IEnumerable<String> indexValues = folder.ListValues;
                    string chronoName = null;

                    for (int i = 0; i < indexList.Count; i++)
                    {
                        if (indexList.ElementAt(i).Type == (int)IndexDomainServiceEnums.IndexType.TypeChrono)
                        {
                            chronoName = indexValues.ElementAt(i);
                            break;
                        }
                    }
                    if (!String.IsNullOrEmpty(chronoName))
                    {
                        GlobalWebContext.BusinessEntitiesDomainContext.ReleaseChrono(chronoName);
                    }
                }

                foreach (Folder f in listFolder)
                {
                    Folder currentFolder = f;

                    BusinessEntitiesDomainContext ds = GlobalWebContext.BusinessEntitiesDomainContext;
                    var query = ds.GetWorkflowInstancesByFolderIdQuery(
                        f.FolderTypeIdentifier,
                        f.Identifier,
                        GlobalWebContext.CurrentUser.UserId,
                        true);
                    ds.Load(
                        query,
                        result =>
                        {
                            if (result.Entities.Any(flow => !flow.IsEnded))
                            {
                                MessageBoxChildWindow message = new MessageBoxChildWindow("",
                                    "Il existe des flux en cours pour le dossier sélectionné.",
                                    MessageBoxButtons.Ok,
                                    MessageBoxIcon.Warning);
                                message.ShowDialog();
                            }
                            else
                            {
                                var queryDoc = GlobalWebContext.BusinessEntitiesDomainContext.DeleteFolderQuery(currentFolder.FolderTypeIdentifier, currentFolder.Iddoc, currentFolder.Identifier);
                                GlobalWebContext.BusinessEntitiesDomainContext.Load(queryDoc, OnDeleteDocumentQueryCallback, currentFolder.Identifier);
                            }
                        },
                        null);

                }
            }
            catch (Exception ex)
            {
                MessageBoxChildWindow messageDeleteFolder = new MessageBoxChildWindow("", "Error : " + Environment.NewLine + ex.Message,
                                                                MessageBoxButtons.Ok, MessageBoxIcon.Error);
                messageDeleteFolder.ShowDialog();
            }
        }

        /// <summary>
        /// Delete folder callback. This method removes the deleted folder into the source collection of the griViewDoc
        /// </summary>
        /// <param name="result"></param>
        private void OnDeleteDocumentQueryCallback(LoadOperation<NetBay.Core.BusinessEntities.ReturnObject> result)
        {
            if (result.Error != null)
            {
                //Logger.Write("EXCEPTION : " + Environment.NewLine + p_oResult.Error, Logger.Level.Error);
            }
            else
            {
                long folderIdToDeleteRef = (long)result.UserState;

                Dictionary<string, Object> elementToDelete = m_oSource.Cast<Dictionary<string, Object>>().FirstOrDefault(item => (long)item["Identifier"] == folderIdToDeleteRef);

                if (elementToDelete != null)
                    m_oSource.Remove(elementToDelete);

                InitlabelNbrOfFolderResults();
            }
        }

        #endregion

        #region Export Excel
        /// <summary>
        /// Export document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonExportClick(object sender, RoutedEventArgs e)
        {
            OnExportClick();
        }

        private void OnExportClick()
        {
            List<Folder> selectedFolders = new List<Folder>();
            if (GridViewDoc.SelectedItems != null && GridViewDoc.SelectedItems.Count > 0)
            {
                selectedFolders.AddRange(GridViewDoc.SelectedItems.Cast<Dictionary<string, Object>>().Select(item => _listFolders.Where(f => f.Identifier == (long)item["Identifier"]).FirstOrDefault()).Where(f => f != null));

                string data = Report.FolderExport(selectedFolders);
                SaveFileDialog sfd = new SaveFileDialog
                {
                    DefaultExt = "csv",
                    Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
                    FilterIndex = 1
                };

                try
                {


                    if (sfd.ShowDialog() == true)
                    {
                        using (Stream stream = sfd.OpenFile())
                        {
                            using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                            {
                                writer.Write(data);
                                writer.Close();
                            }
                            stream.Close();
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }
        #endregion

        #region Print Documents

        private void OnCreateReportClick()
        {
            List<String> selectedFolderIds = new List<String>();
            foreach (Dictionary<string, Object> dict in GridViewDoc.SelectedItems)
            {
                if (dict != null)
                {
                    Folder selectedFolder = _listFolders.Where(f => f.Identifier == (long)dict["Identifier"]).FirstOrDefault();
                    if (selectedFolder != null)
                    {
                        selectedFolderIds.Add(Convert.ToString(selectedFolder.Identifier));
                    }
                }
            }
            CreateReportWindow createReportWindow = new CreateReportWindow(OrganizationSelected.Identifier, FolderTypeSelected.Identifier, ListIndex, String.Join(",", selectedFolderIds.ToArray()));
            createReportWindow.Show();
        }

        private void OnPrintMenuClick()
        {
            Dictionary<string, Object> dict = GridViewDoc.SelectedItem as Dictionary<string, Object>;
            if (dict != null)
            {
                Folder selectedFolder = _listFolders.Where(f => f.Identifier == (long)dict["Identifier"]).FirstOrDefault();

                if (selectedFolder != null)
                {
                    var query = GlobalWebContext.BusinessEntitiesDomainContext.GetDocumentsQuery(
                        selectedFolder.FolderTypeIdentifier,
                        selectedFolder.Identifier);

                    GlobalWebContext.BusinessEntitiesDomainContext.Load(query, OnGetDocumentByFolderForPrintQueryCallback, null);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="result"></param>
        public void OnGetDocumentByFolderForPrintQueryCallback(LoadOperation<NetBay.Core.BusinessEntities.Document> result)
        {
            List<NetBay.Core.BusinessEntities.Document> folderDocuments = new List<NetBay.Core.BusinessEntities.Document>(result.Entities);

            List<string> documentToPrint = folderDocuments.Select(d => System.IO.Path.Combine(GlobalWebContext.ParameterStorage, d.RelativePath, d.ImageName)).ToList();
            PrintDocumentsInPDFFormat(documentToPrint);
        }

        /// <summary>
        /// Prints the documents in PDF format.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        private void PrintDocumentsInPDFFormat(List<string> fileName)
        {

            if ((fileName != null) && (fileName.Count > 0))
            {
                SplashScreenManager.Wait(this);


                WCFServiceClient serviceClient = ServiceManager.GetRioWCFServiceClient();
                serviceClient.GetPrintableVersionOfDocumentFullPathCompleted += L_oWCFServiceClient_GetPrintableVersionOfDocumentFullPathCompleted;
                serviceClient.GetPrintableVersionOfDocumentFullPathAsync(new ObservableCollection<string>(fileName), ServiceManager.GetLicenseKey());
                BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();
                var query = businessEntitiesDomainContext.AddActionHistoricQuery((int)Constant.UserActions.IMPRESSION, 0, 0, null,
                                                fileName.ToString(";"));
                businessEntitiesDomainContext.Load(query);
            }
        }

        /// <summary>
        /// Handles the GetPrintableVersionOfDocumentFullPathCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.GetPrintableVersionOfDocumentFullPathCompletedEventArgs"/> instance containing the event data.</param>
        private void L_oWCFServiceClient_GetPrintableVersionOfDocumentFullPathCompleted(object sender, GetPrintableVersionOfDocumentFullPathCompletedEventArgs e)
        {
            SplashScreenManager.Stop(this);

            string folder = e.Result.Value;
            string path =
                System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri.Replace(
                    System.Windows.Browser.HtmlPage.Document.DocumentUri.LocalPath, String.Empty);
            const string filename = "/Rio.Application.OpenPDF.aspx";
            string parameters = "?fld=" + System.Windows.Browser.HttpUtility.UrlEncode(folder);
            VariableDomainContext variableDomainContext = new VariableDomainContext();
            variableDomainContext.GetAppDomainAppVirtualPath(str => System.Windows.Browser.HtmlPage.Window.Navigate(
                str.Value == "/"
                    ? new Uri(
                          path + filename + parameters,
                          UriKind.Absolute)
                    : new Uri(
                          path + str.Value + filename +
                          parameters, UriKind.Absolute),
                "_blank",
                "toolbar=no,location=no,status=no,menubar=no,resizable=yes,titlebar=no")
                                                           , null);
        }

        #endregion

        #region Alert

        private void ButtonAlertClick(object sender, RoutedEventArgs e)
        {
            List<Folder> selectedFolders = new List<Folder>();
            if (GridViewDoc.SelectedItems != null && GridViewDoc.SelectedItems.Count > 0)
            {
                selectedFolders.AddRange(GridViewDoc.SelectedItems.Cast<Dictionary<string, Object>>().Select(item => _listFolders.Where(f => f.Identifier == (long)item["Identifier"]).FirstOrDefault()).Where(f => f != null));

                CreateAlertWindow createAlertWindow = new CreateAlertWindow(selectedFolders);
                createAlertWindow.Closed += CreateAlertWindowClosed;
                createAlertWindow.ShowDialog();

            }
        }

        private void CreateAlertWindowClosed(object sender, EventArgs e)
        {
            CreateAlertWindow createAlertWindow = (CreateAlertWindow)sender;
            createAlertWindow.Closed -= CreateAlertWindowClosed;

            if (createAlertWindow.DialogResult == true)
            {
                if (CreateAlertEventHandler != null)
                {
                    CreateAlertEventHandler(this, null);
                }
            }
        }

        private void OpenFolderAlertWindow(long folderId)
        {
            Folder selectedFolder = _listFolders.Where(f => f.Identifier == folderId).FirstOrDefault();

            if (selectedFolder != null && selectedFolder.NbAlert > 0)
            {
                AlertListWindow alertListWindow = new AlertListWindow(selectedFolder);

                alertListWindow.Closed += AlertListWindowClosed;
                alertListWindow.ShowDialog();
            }
            else
            {
                LoadModificationSelectedFolder(selectedFolder);
            }
        }

        private void AlertListWindowClosed(object sender, EventArgs e)
        {
            AlertListWindow alertListWindow = (AlertListWindow)sender;
            if (alertListWindow.HasDeleted)
            {
                OnRefreshSearchResult();
            }
        }

        #endregion

        #region GridView

        /// <summary>
        /// Inititialize folder search result GridView        
        /// </summary>
        public void InitGridViewFolderSearch()
        {

            GridViewDoc.FilterDescriptors.Clear();
            GridViewDoc.GroupDescriptors.Clear();
            GridViewDoc.SortDescriptors.Clear();
            GridViewDoc.Columns.Clear();

            GridViewSelectColumn gridViewSelectColumn = new GridViewSelectColumn { MinWidth = 30 };
            GridViewDoc.Columns.Add(gridViewSelectColumn);

            GridViewImageColumn folderImageColumn = new GridViewImageColumn
            {
                UniqueName = "Folder",
                IsReadOnly = true,
                Header = String.Empty,
                Width = 40,
                ImageHeight = 32,
                ImageWidth = 32,
                DataMemberBinding = new Binding("[NbDoc]")
                {
                    Converter = new FolderToImageConverter()
                }
            };
            GridViewDoc.Columns.Add(folderImageColumn);

            FolderAlertColumn alertColumn = new FolderAlertColumn
            {
                UniqueName = "NbAlert",
                IsReadOnly = true,
                Header = labelAlerts,
                DataMemberBinding = new Binding("[NbAlert]"),
                OpenAlertWindowCommand = new RelayCommand<long>(OpenFolderAlertWindow)
            };

            GridViewDoc.Columns.Add(alertColumn);

            // Document number column
            GridViewDataColumn nbDocColumn = new GridViewDataColumn
            {
                IsReadOnly = true,
                MinWidth = 100,
                Header = LabelHeaderColumnNbDoc,
                DataType = typeof(int),
                DataMemberBinding = new Binding("[NbDoc]")
            };
            GridViewDoc.Columns.Add(nbDocColumn);

            foreach (Index t in ListIndex)
            {
                if (t.IsVisible)
                {
                    GridViewDoc.Columns.Add(new GridViewDataColumn
                    {
                        UniqueName = t.Indentifier.ToString(),
                        IsReadOnly = true,
                        Header = t.IndexLabel,
                        MinWidth = 150,
                        DataType = GetIndexType(t),
                        DataFormatString =
                            GetIndexType(t) == typeof(DateTime?) ? DateStringFormatterHelper.GetDateStringFormatter() : "",
                        DataMemberBinding =
                            new Binding("[index" + t.Indentifier + "]") { Converter = new IndexValueConverter() }
                    });
                }
            }

            // Document number column
            GridViewDataColumn creationDateDocColumn = new GridViewDataColumn
            {
                UniqueName = "CreationDate",
                IsReadOnly = true,
                MinWidth = 100,
                Header = LabelHeaderColumnCreationDate,
                DataType = typeof(DateTime),
                DataFormatString = DateStringFormatterHelper.GetDateStringFormatter(),
                DataMemberBinding = new Binding("[CreationDate]")
            };
            GridViewDoc.Columns.Add(creationDateDocColumn);

            // Document number column
            GridViewDataColumn modificationDateDocColumn = new GridViewDataColumn
            {
                UniqueName = "ModificationDate",
                IsReadOnly = true,
                MinWidth = 100,
                Header = LabelHeaderColumnModificationDate,
                DataType = typeof(DateTime),
                DataFormatString = DateStringFormatterHelper.GetDateStringFormatter(),
                DataMemberBinding = new Binding("[ModificationDate]")
            };
            GridViewDoc.Columns.Add(modificationDateDocColumn);


        }

        private void GridViewDocSelectionChanged(object sender, SelectionChangeEventArgs e)
        {
            if (GridViewDoc.SelectedItems.Count != 1)
            {
                buttonDisplay.IsEnabled = false;
                PasteMenuContextMenu.IsEnabled = false;

                if (GridViewDoc.SelectedItems.Count == 0)
                {
                    buttonDelete.IsEnabled = false;
                    buttonExport.IsEnabled = false;
                    buttonAlert.IsEnabled = false;
                    buttonDownload.IsEnabled = false;
                }
                else
                {
                    buttonDelete.IsEnabled = GlobalWebContext.GetUserCanDelete(FolderTypeSelected);
                    buttonExport.IsEnabled = GlobalWebContext.GetUserCanDownload(FolderTypeSelected); 
                    buttonAlert.IsEnabled = true;
                    buttonDownload.IsEnabled = GlobalWebContext.GetUserCanDownload(FolderTypeSelected); 
                }
            }
            else
            {
                PasteMenuContextMenu.IsEnabled = isPastEnabled;
                buttonDisplay.IsEnabled = true;
                buttonDelete.IsEnabled = GlobalWebContext.GetUserCanDelete(FolderTypeSelected); ;
                buttonExport.IsEnabled = GlobalWebContext.GetUserCanDownload(FolderTypeSelected); 
                buttonAlert.IsEnabled = true;
                buttonDownload.IsEnabled = (GlobalWebContext.GetUserCanDownload(FolderTypeSelected)); 
            }
        }

        private void GridViewDocDeleting(object sender, GridViewDeletingEventArgs e)
        {
            e.Cancel = true;
            OnFolderDeleteClick();
        }

        #endregion

        #region Paste

        /// <summary>
        /// Past documents in the selected folder
        /// </summary>
        private void OnPastClick()
        {
            if (GridViewDoc.SelectedItems != null && GridViewDoc.SelectedItems.Count == 1)
            {
                Folder selectedFolder = GridViewDoc.SelectedItems.Cast<Dictionary<string, Object>>().Select(item => _listFolders.Where(f => f.Identifier == (long)item["Identifier"]).FirstOrDefault()).Where(f => f != null).First();
                if (selectedFolder != null)
                {
                    PasteDocuments(selectedFolder);
                }
            }
        }

        #endregion

        /// <summary>
        /// Translation
        /// </summary>
        public override void InitLabel()
        {
            base.InitLabel();

            LabelHeaderColumnNbDoc = Resx.GetLabel(ResxFolder.NB_DOC);
            LabelHeaderColumnCreationDate = Resx.GetLabel(ResxFolder.CREATION_DATE_HEADER);
            LabelHeaderColumnModificationDate = Resx.GetLabel(ResxFolder.LAST_MODIFICATION_DATE_HEADER);
            m_ssSplashScreen.Message = Resx.GetLabel(ResxCommon.SPLASHSCREEN_MESSAGE);
            labelMessageDeleteConfirmation = Resx.GetLabel(ResxFolder.DELETE_CONFIRMATION_FOLDER);
            buttonDelete.Header = Resx.GetLabel(ResxCommon.DELETE);
            buttonExport.Header = Resx.GetLabel(ResxCommon.EXPORT);
            buttonDisplay.Header = Resx.GetLabel(ResxCommon.DISPLAY);
            buttonAlert.Header = Resx.GetLabel(ResxCommon.ALERT);
            buttonDownload.Header = Resx.GetLabel(ResxCommon.DOWNLOAD);

            labelNbrOfFolderResults = Resx.GetLabel(ResxFolder.NBR_OF_FOLDER_RESULT);
            labelAlerts = Resx.GetLabel(ResxFolder.ALERT_HEADER);

            DeleteItemContextMenu.Header = Resx.GetLabel(ResxCommon.DELETE);
            ExportExcelContextMenu.Header = Resx.GetLabel(ResxCommon.EXPORT);
            OpenFolderContextMenu.Header = Resx.GetLabel(ResxFolder.OPEN_FOLDER);
            AddDocumentContextMenu.Header = Resx.GetLabel(ResxFolder.ADD_DOCUMENT);
            DisplayFolderNoteContextMenu.Header = Resx.GetLabel(ResxFolder.DISPLAY_NOTE);
            PrintMenuContextMenu.Header = Resx.GetLabel(ResxCommon.PRINT);
            //CreateReportContextMenu.Header = Resx.GetLabel(ResxFolder.CREATE_PDF_REPORT);
            PasteMenuContextMenu.Header = Resx.GetLabel(ResxCommon.PASTE);
            DownloadFolderContextMenu.Header = Resx.GetLabel(ResxCommon.DOWNLOAD);
        }

        /// <summary>
        /// Enable to load folder list in gridview
        /// </summary>
        private void LoadListFolders()
        {
            //Build a dictionnary list to bind folder and index value into the gridview
            List<Dictionary<string, Object>> listRow = new List<Dictionary<string, Object>>();

            foreach (Folder f in _listFolders)
            {
                Dictionary<string, Object> dict = new Dictionary<string, Object>
                                                      {
                                                          {"Identifier", f.Identifier},
                                                          {"NbDoc", f.NbDoc},
                                                          {"NbAlert", f.NbAlert},
                                                          {"CreationDate", f.CreationDate},
                                                          {"ModificationDate", f.ModificationDate}
                                                      };

                //For every value from ListValues, we have "ID;VALUE" for value list type index and user list type index, and we have "VALUE;VALUE" for the other index type
                //because for value list type index and user list type index we need the value to display and id for identify the value (for the consultation screen for exemple, to select the item in the combobox) 
                List<string> indexValues = new List<string>(f.ListValues);
                List<Index> indexes = new List<Index>(f.ListIndex);

                for (int i = 0; i < indexes.Count; i++)
                {
                    if (indexes[i].IsVisible)
                    {
                        if (indexes[i].Type.Equals((int)IndexDomainServiceEnums.IndexType.Date))
                        {
                            if (indexValues[i] != null && indexValues[i] != String.Empty)
                            {
                                dict.Add("index" + indexes[i].Indentifier, ToDateTime(indexValues[i]));
                            }
                            else
                            {
                                dict.Add("index" + indexes[i].Indentifier, null);
                            }
                        }
                        else
                        {
                            dict.Add("index" + indexes[i].Indentifier, indexValues[i]);
                        }
                    }
                }

                listRow.Add(dict);
            }

            if (listRow.Count == 0)
            {
                buttonDisplay.IsEnabled = false;
                buttonDelete.IsEnabled = false;
                buttonExport.IsEnabled = false;
                buttonAlert.IsEnabled = false;
                buttonDownload.IsEnabled = false;
            }

            Folders = new QueryableCollectionView(listRow);
            DataPagerDoc.Source = Folders;

            InitlabelNbrOfFolderResults();
        }

        private void InitlabelNbrOfFolderResults()
        {
            LabelNbrOfFolderResults.Visibility = Visibility.Visible;
            LabelNbrOfFolderResults.Text = String.Format(labelNbrOfFolderResults, Folders.ItemCount);
        }

        private void OnCellDoubleClick(object sender, RadRoutedEventArgs args)
        {
            OpenFolderClick();
        }

        public override void ClearResults()
        {
            if (Folders != null)
                Folders.Dispose();
        }

        #region Download Folders

        /// <summary>
        /// Handles the Click event of the buttonDownload control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Windows.RadRoutedEventArgs"/> instance containing the event data.</param>
        private void ButtonDownloadClick(object sender, RadRoutedEventArgs e)
        {
            OnDownloadFolderClick();
        }

        /// <summary>
        /// Called when [download folder click].
        /// </summary>
        private void OnDownloadFolderClick()
        {
            var selectedFolders = GridViewDoc.SelectedItems.Cast<Dictionary<string, Object>>().Select(item => _listFolders.Where(f => f.Identifier == (long)item["Identifier"]).FirstOrDefault()).Where(f => f != null);

            if (selectedFolders.Count() > 0)
            {
                var folderType = GlobalWebContext.CurrentUser.GroupList.SelectMany(g => g.OrganizationList).SelectMany(o => o.FolderTypesList).Where(ft => ft.Identifier == selectedFolders.FirstOrDefault().FolderTypeIdentifier).FirstOrDefault();

                if (folderType != null)
                {
                    CursorWait(this);

                    SplashScreenManager.SplashScreen.Message = Resx.GetLabel(ResxSearchPage.DOWNLOADFOLDER_TITLE);
                    SplashScreenManager.SplashScreen.MessageDetail = Resx.GetLabel(ResxSearchPage.DOWNLOADFOLDER_SPLASHSREEN_STEP1);

                    ZipFoldersManager zipFoldersManager = new ZipFoldersManager(folderType.OrganizationIdentifier, folderType, selectedFolders.ToList());
                    zipFoldersManager.InitializationFinished += ZipFoldersManagerInitializationFinished;
                    zipFoldersManager.Initialization();
                }
            }
        }

        /// <summary>
        /// Handles the InitializationFinished event of the zipFoldersManager control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ZipFoldersManagerInitializationFinished(object sender, EventArgs e)
        {
            ZipFoldersManager zipFoldersManagerSource = sender as ZipFoldersManager;

            if (zipFoldersManagerSource != null)
            {
                SplashScreenManager.SplashScreen.MessageDetail = Resx.GetLabel(ResxSearchPage.DOWNLOADFOLDER_SPLASHSREEN_STEP2);

                zipFoldersManagerSource.InitializationFinished -= ZipFoldersManagerInitializationFinished;
                zipFoldersManagerSource.ProcessFinished += ZipFoldersManagerSourceProcessFinished;
                zipFoldersManagerSource.Process();
            }
        }

        /// <summary>
        /// Handles the ProcessFinished event of the zipFoldersManagerSource control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ZipFoldersManagerSourceProcessFinished(object sender, EventArgs e)
        {
            ZipFoldersManager zipFoldersManagerSource = sender as ZipFoldersManager;

            if (zipFoldersManagerSource != null)
            {
                SplashScreenManager.SplashScreen.MessageDetail = Resx.GetLabel(ResxSearchPage.DOWNLOADFOLDER_SPLASHSREEN_STEP3);

                zipFoldersManagerSource.ProcessFinished -= ZipFoldersManagerSourceProcessFinished;
                zipFoldersManagerSource.GetZipFinished += ZipFoldersManagerSourceGetZipFinished;
                zipFoldersManagerSource.GetZip();
            }
        }

        /// <summary>
        /// Zips the folders manager source get zip finished.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        /// <param name="totalFolders">The total folders.</param>
        /// <param name="totalFoldersProcessed">The total folders processed.</param>
        private void ZipFoldersManagerSourceGetZipFinished(object sender, byte[] e, int totalFolders, int totalFoldersProcessed)
        {
            ZipFoldersManager zipFoldersManagerSource = sender as ZipFoldersManager;

            if (zipFoldersManagerSource != null)
            {
                zipFoldersManagerSource.GetZipFinished -= ZipFoldersManagerSourceGetZipFinished;

                CursorNormal(this);

                if (e == null)
                {
                    MessageBoxChildWindow errorMessageBox = new MessageBoxChildWindow(
                        Resx.GetLabel(ResxCommon.ERROR),
                        Resx.GetLabel(ResxSearchPage.DOWNLOADFOLDER_ERROR),
                        MessageBoxButtons.Ok,
                        MessageBoxIcon.Error);

                    errorMessageBox.ShowDialog();
                }
                else
                {
                    DownloadFolderChildWindow downloadFolderChildWindow = new DownloadFolderChildWindow(e)
                    {
                        Sender = zipFoldersManagerSource,
                        TotalFolders = totalFolders,
                        TotalFoldersProcessed = totalFoldersProcessed
                    };

                    downloadFolderChildWindow.Closed += downloadFolderChildWindow_Closed;
                    downloadFolderChildWindow.ShowDialog();
                }
            }
        }

        /// <summary>
        /// Handles the Closed event of the downloadFolderChildWindow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Windows.Controls.WindowClosedEventArgs"/> instance containing the event data.</param>
        private void downloadFolderChildWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            DownloadFolderChildWindow downloadFolderChildWindow = sender as DownloadFolderChildWindow;

            if (downloadFolderChildWindow != null)
            {
                downloadFolderChildWindow.Closed -= downloadFolderChildWindow_Closed;

                var zipFoldersManager = downloadFolderChildWindow.Sender as ZipFoldersManager;

                if (zipFoldersManager != null)
                    zipFoldersManager.ClearServer();
            }
        }

        #endregion
    }
}
